//
//  RwdcomposeView.swift
//  Weibo_rwd
//
//  Created by 任文迪 on 16/7/17.
//  Copyright © 2016年 spaceX. All rights reserved.
//

import UIKit

class RwdcomposeView: UIView {
    //懒加载一个imageview
    private lazy var backgroundImage : UIImageView = UIImageView(image: UIImage.getScreenShot().applyLightEffect())
    
    //重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //setUpUI方法
    private func setupUI() {
        
        backgroundColor = UIColor.yellowColor()
        
        self.frame.size = CGSize(width: UIScreen.mainScreen().bounds.size.width, height: UIScreen.mainScreen().bounds.size.height)
        
        //添加图片背景
        addSubview(backgroundImage)
        backgroundImage.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self).offset(UIEdgeInsetsZero)
        }
        
        loadComposeList()
        addComposeButton()
        
    }

    
    
    
    //添加移除的方法
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        removeFromSuperview()
        
    }
    
    //读取plist文件
    private func loadComposeList() ->[RwdcomposeModel] {
        //路径
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        //读取文件
        let composeDictArr = NSArray(contentsOfFile: path)
        
        //准备临时数组
        var tempArray = [RwdcomposeModel]()
        
        for dict in composeDictArr! {
            
            let composeModel = RwdcomposeModel(dict: dict as! [String : AnyObject])
            
            tempArray.append(composeModel)
            
        }
        return tempArray
    }
    
    
    //添加button
    
    private func addComposeButton() {
        
        //  按钮的宽度
        let buttonWidth: CGFloat = 80
        //  按钮的高度
        let buttonHeight: CGFloat = 110
        //按钮的间距
        let buttonMargin: CGFloat = (width - 3 * buttonWidth) / 4
        //获取plist的数据
        let composeArr = loadComposeList()
        
        for (i,value) in composeArr.enumerate() {
            
            let button = RwdcomposeButton()
            
            button.width = buttonWidth
            button.height = buttonHeight
            
            //列号
            let numOfCol = i % 3
            //行号
            let numOfRow = i / 3
            
            //  计算x坐标
            button.x = buttonWidth * CGFloat(numOfCol) + CGFloat(numOfCol + 1) * buttonMargin
            
            //  计算y坐标
            button.y = buttonHeight * CGFloat(numOfRow) + CGFloat(numOfRow) * buttonMargin
            
            button.setImage(UIImage(named: value.icon!), forState: .Normal)
            button.setTitle(value.title!, forState: .Normal)
            
            addSubview(button)
            
        }
        
        
        
    }
    
    
    
    
}
